package blog.model;

import blog.beans.Comment;
import blog.utils.HibernateUtil;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

/**
 * @author johdah <info@johandahlberg.com>
 */
public class CommentHelper {
    Session session = null;
    
    public CommentHelper() {
        this.session = HibernateUtil.getSessionFactory().getCurrentSession();
    }
    
    public List<Comment> getComments() {
        List<Comment> comments = null;
        
        try {
            Transaction tx = session.beginTransaction();
            Query q = session.createQuery("from Comment");
            comments = (List<Comment>) q.list();
        } catch(Exception e) {
            e.printStackTrace();
        }
        
        return comments;
    }
    
    public List<Comment> getCommentsByPostId(Integer post_id) {
        List<Comment> comments = null;
        
        try {
            Transaction tx = session.beginTransaction();
            Query q = session.createQuery("from Comment as comment where comment.PId=" + post_id);
            comments = (List<Comment>) q.list();
        } catch(Exception e) {
            e.printStackTrace();
        }
        
        return comments;
    }
    
    public boolean setComments(Comment comment) {
        try {
            Transaction tx = session.beginTransaction();
            session.save(comment);
            tx.commit();
            return true;
        } catch(Exception e) {
            return false;
        }
    }
}